package pers.richard.ormybatis.bean.mapping;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import pers.richard.ormybatis.bean.AbstractDomain;
import pers.richard.ormybatis.util.CaseFormatUtil;

/**
 * insert单个对象 mapping参数bean
 */
public class InsertMappingBean extends BaseMappingBean{
	/**  po 对象 map形式  */
	private Map<String, Object> poMap = new LinkedHashMap<>();
	
	/** 新增主键ID值 */
	private Object insertId;

	public InsertMappingBean(){}
	
	public InsertMappingBean(String tableName, String primaryKeyName, AbstractDomain po, boolean lowerUnderscore){
		super(tableName, primaryKeyName);
		Field[] fields = po.getClass().getDeclaredFields();
		Date now = new Date();
		for (Field field : fields) {
			String fieldName = field.getName();
			Object value = BeanUtil.getProperty(po, fieldName);
			if (StrUtil.equalsAnyIgnoreCase(fieldName, CREATE_FIELD_PROPERTY) && ObjectUtil.isEmpty(value) ) {
				value = now;
			}
			if (StrUtil.equalsAnyIgnoreCase(fieldName, UPDATE_FIELD_PROPERTY) && ObjectUtil.isEmpty(value) ) {
				value = now;
			}
			if (StrUtil.equalsAnyIgnoreCase(fieldName, "isDeleted", "updateVersion") && ObjectUtil.isEmpty(value) ) {
				value = 0;
			}
			if (value != null) {
				if (value instanceof String) {
					value = ((String) value).trim();
				}
			}
			String key =  lowerUnderscore ? CaseFormatUtil.toLowerUnderscore(field.getName()) : CaseFormatUtil.toLowerCamel(field.getName());
			poMap.put(key, value);
		}
	}
	
	public Map getPoMap() {return poMap;}
	public void setPoMap(Map<String, Object> poMap) {this.poMap = poMap;}
	
	public Object getInsertId() {return insertId;}
	public void setInsertId(Object insertId) {this.insertId = insertId;}
	
	
}
